/**
 * hnjz.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.hnjz.sys.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

import com.hnjz.common.AppException;
import com.hnjz.common.FyWebResult;
import com.hnjz.common.PKUtil;
import com.hnjz.common.YnEnum;
import com.hnjz.common.dao.domain.FyCounter;
import com.hnjz.common.security.CtxUtil;
import com.hnjz.common.security.OperateUtil;
import com.hnjz.common.util.LogUtil;
import com.hnjz.sys.role.Role;
import com.hnjz.sys.role.RoleMapper;

/**
 * 用户管理
 * 
 * @author wumi
 * @version $Id: UserManager.java, v 0.1 Jan 17, 2013 9:32:53 AM wumi Exp $
 */
@Service("userManager")
public class UserManager {
    /**日志*/
    private static final Log    log          = LogFactory.getLog(UserManager.class);
    /**用户默认的密码*/
    private static final String DEFAULT_PASS = "888888";
    @Autowired
    private Md5PasswordEncoder  md5PasswordEncoder;

    @Autowired
    private UserMapper          userMapper;
    @Autowired
    private RoleMapper          roleMapper;

    /**用户的缓存，key为usrid,value为用户对应的部门*/
    private Map<String, User>   users        = new ConcurrentHashMap<String, User>();

    /**
     * 根据用户Id获取用户
     * 
     * @param id 用户ID
     * @return 用户
     */
    public User getUser(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        User user = users.get(id);
        if (null == user) {
            user = userMapper.findById(id);
            users.put(id, user);
        }
        return user;
    }

    /**
     * 根据用户Id获取用户
     * 
     * @param id 用户ID
     * @return 用户
     */
    public Role findRoleByUserId(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return this.roleMapper.findRoleByUserId(id);
    }

    /**
     * 查询用户列表
     * 
     * @param name 搜索条件，可以按名称，备注搜索
     * @param page 第几页
     * @param pageSize 每页显示多少条
     * @return 功能菜单列表
     * @throws Exception 
     */
    public FyWebResult queryUser(String name, String page, String pageSize) {
        User u = new User();
        u.setName(name);
        long count = this.userMapper.selectCountByPage(u);
        FyCounter c = new FyCounter();
        c.setNum(count);
        c.setCurrentPage(Integer.parseInt(page));
        c.setPerPageNum(pageSize);
        c.execute();
        if (log.isDebugEnabled()) {
            log.debug(c.getStartItem() + "：" + c.getPerPageNum());
        }
        RowBounds rbs = new RowBounds(c.getStartItem(), c.getPerPageNum());
        FyWebResult fy = new FyWebResult(c);
        List<User> users = this.userMapper.findListByPage(u, rbs);
        List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
        Map<String, String> dataObject = null;
        for (User ele : users) {
            dataObject = new HashMap<String, String>();
            dataObject.put("id", ele.getId());
            dataObject.put("name", ele.getName());
            dataObject.put("userName", ele.getUsername());
            dataObject.put("sj1", ele.getShoujihao());
            dataObject.put("sj2", ele.getShouji2());
            dataObject.put("operate", OperateUtil.getOperate(ele.getId()));
            rows.add(dataObject);
        }
        fy.setRows(rows);
        if (log.isDebugEnabled()) {
            log.debug("查询结果：" + LogUtil.m(fy));
        }
        return fy;
    }

    /**
     * 保存一个用户
     * 
     * @param frm {@link UserForm}
     */
    public void saveUser(UserForm frm) throws AppException {
        //用户登录名不能重复
        long count = this.userMapper.selectCountByLoginName(frm.getUsername(), frm.getId());
        if (count > 0) {
            throw new AppException("用户登录名称不能重复！");
        }
        User po = null;
        User user = CtxUtil.getCurUser();
        Date cur = new Date();
        if (StringUtils.isNotBlank(frm.getId())) {
            po = this.userMapper.findById(frm.getId());
        } else {
            po = new User();
            po.setId(PKUtil.uuid());
            po.setCreater(user.getId());
            po.setCreateTime(cur);

        }
        String password = md5PasswordEncoder.encodePassword(DEFAULT_PASS, null);
        po.setPassWord(password);
        po.setName(frm.getName());
        po.setUserName(frm.getUsername());
        po.setShouji2(frm.getShouji2());
        po.setShoujihao(frm.getShoujihao());
        if (StringUtils.isNotBlank(frm.getIssys())) {
            po.setIsSys(YnEnum.Y.getCode());
        } else {
            po.setIsSys(YnEnum.N.getCode());
        }
        po.setIsActive(YnEnum.Y.getCode());
        po.setUpdateby(user.getId());
        po.setUpdateTime(cur);
        if (StringUtils.isNotBlank(frm.getId())) {
            this.userMapper.update(po);
        } else {
            this.userMapper.save(po);
        }

        if (StringUtils.isNotBlank(po.getId())) {
            users.remove(po.getId());
        }

        //删除用户的角色
        this.userMapper.deleteRoleByUser(frm.getId());

        //保存角色
        if (StringUtils.isNotBlank(frm.getJiece())) {
            UserRole u = new UserRole();
            u.setId(PKUtil.uuid());
            u.setRole(frm.getJiece());
            u.setUser(po.getId());//frm.getId() frm是从页面中取值，id并没有数据
            this.userMapper.saveUserRole(u);
        }
    }

    /**
     * 保存密码
     * 
     * @param frm {@link UserForm}
     */
    public void resetPas(String id) throws AppException {
        String password = md5PasswordEncoder.encodePassword(DEFAULT_PASS, null);
        this.userMapper.updatePasswordById(password, id);
    }

    /**
     * 保存密码
     * 
     * @param frm {@link UserForm}
     */
    public void savePas(UserForm frm) throws AppException {
        if (!frm.getPassword().equals(frm.getConfirmPassword())) {
            throw new AppException("两次新密码不一致，请重新输入!");
        }
        User user = CtxUtil.getCurUser();
        User po = this.userMapper.findById(user.getId());
        //判断当前密码是否正确
        String old = md5PasswordEncoder.encodePassword(frm.getOldPas(), null);
        if (StringUtils.equals(po.getPassword(), old)) {
            throw new AppException("当前密码不正确!");
        }
        String password = md5PasswordEncoder.encodePassword(frm.getPassword(), null);
        this.userMapper.updatePasswordById(password, user.getId());
    }

    /**
     * 删除用户，用户和角色关系
     * 
     * @param id 用户ID
     */
    public void removeUser(String id) {
        //删除用户和角色的关系
        this.userMapper.deleteRoleByUser(id);
        this.userMapper.deleteById(id);
        users.remove(id);
    }
}
